<!--
 * @version: 
 * @Company:  
 * @Description: 模板设置
 * @FilePath: \src\views\tool\tpl\modal\settings\index.vue
-->
<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="模板设置" width="70%" :keyboard="false" :maskClosable="false" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #content="{ model, field }">
        <monaco-editor ref="monacoEditor" v-model="model[field]" lang="json" />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { getFormConfig } from './config';
  import * as _API from '../../api';
  import { message } from 'ant-design-vue';
  import monacoEditor from '/@/components/Custom/MonacoEditor/index.vue';
  import CRUD from '/@/crud/core/init';
  export default defineComponent({
    name: 'tplForm',
    components: { BasicModal, BasicForm, monacoEditor },
    emits: ['success'],
    setup(_, { emit }) {
      const [registerForm, formMethods] = useForm({
        labelWidth: 100,
        schemas: getFormConfig(),
        showActionButtonGroup: false,
      });
      const crud = CRUD({
        title: '生成模板',
        crudMethod: { ..._API },
        useForm: {
          registerForm,
          formMethods,
        },
      }); // 初始化crud
      const monacoEditor: any = ref(null);

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async ({ record }) => {
        setModalProps({ confirmLoading: false });
        await crud.useForm.formMethods.resetFields();
        await crud.useForm.formMethods.setFieldsValue({ ...record, content: JSON.stringify(record.content) });
      });

      const handleSubmit = async () => {
        try {
          const value = await crud.useForm.formMethods.validate();
          setModalProps({ confirmLoading: true });
          _API.saveSettingsAPI({ ...crud.useForm.formMethods.getFieldsValue() }).then((res: any) => {
            const { code } = res.data;
            if (code == 0) {
              emit('success');
              setTimeout(() => {
                closeModal();
              }, 500);
            } else {
              setModalProps({ confirmLoading: false });
            }
          });
        } catch {
          message.error('操作失败！');
        }
      };
      return { registerModal, registerForm: crud.useForm.registerForm, handleSubmit, monacoEditor };
    },
  });
</script>
